package com.beiye.drivertransport.SubActivity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.ViewGroup;

import com.alibaba.fastjson.JSON;
import com.beiye.drivertransport.R;
import com.beiye.drivertransport.bean.LoginUserBean;
import com.beiye.drivertransport.bean.UpPhotoBean;
import com.beiye.drivertransport.config.AppInterfaceConfig;
import com.beiye.drivertransport.utils.ImageUtil;
import com.beiye.drivertransport.utils.LogUtils;
import com.beiye.drivertransport.utils.MessageEvent;
import com.beiye.drivertransport.utils.MessageEventTest;
import com.beiye.drivertransport.utils.MessageEventTest1;
import com.beiye.drivertransport.utils.UserManger;
import com.beiye.drivertransport.view.ChangeView;
import com.sandrios.sandriosCamera.internal.SandriosCamera;
import com.sandrios.sandriosCamera.internal.configuration.CameraConfiguration;
import com.sandrios.sandriosCamera.internal.manager.CameraOutputModel;

import org.greenrobot.eventbus.EventBus;

import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

//考试人脸识别拍照
public class TakefacePhotoScrollsActivity extends AppCompatActivity {
    private int screenWidth;
    private int screenHeight;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_takeface_photo_scrolls);
        Bundle bundle = getIntent().getExtras();
        final Integer sn = bundle.getInt("daikaosn");
        final String snapTime = bundle.getString("snapTime");
        String personphotoUrl = bundle.getString("personphotoUrl");
        int faceRecgMark = bundle.getInt("faceRecgMark");
        LoginUserBean userInfo = UserManger.getUserInfo();
        LoginUserBean.DataBean data = userInfo.getData();
        final String userId = data.getUserId();
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);// 取得窗口属性
        // 窗口的宽度
        screenWidth = dm.widthPixels;
        // 窗口高度
        screenHeight = dm.heightPixels;
        ViewGroup viewGroup = (ViewGroup) this.findViewById(android.R.id.content);
        ChangeView.changeViewSize(viewGroup, screenWidth, screenHeight);
        SharedPreferences sp = getSharedPreferences("TAG",
                Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putInt("TAG", 2);
        editor.commit();
        SandriosCamera
                .with(TakefacePhotoScrollsActivity.this)
                .setShowPicker(false)
                .setShowPickerType(CameraConfiguration.VIDEO)
                .setVideoFileSize(20)
                .setMediaAction(CameraConfiguration.MEDIA_ACTION_BOTH)
                .enableImageCropping(false)
                .launchCamera(new SandriosCamera.CameraCallback() {
                    @Override
                    public void onComplete(CameraOutputModel model) {

                        String url = model.getPath();
                        File file = new File(url);
                        try {
                            FileInputStream fis = new FileInputStream(file);
                            Bitmap bitmapByUrl = BitmapFactory.decodeStream(fis);
                            bitmapByUrl = compressScale(bitmapByUrl);
                            SharedPreferences sp = getSharedPreferences("CameraSwitchView",
                                    Context.MODE_PRIVATE);
                            int action = sp.getInt("action", 0);
                            if (action == 0) {
                                bitmapByUrl = rotaingImageView(-90, bitmapByUrl);
                            } else if (action == 1) {
                                bitmapByUrl = rotaingImageView(90, bitmapByUrl);
                            }

//                            SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss ");
//                            Date curDate = new Date(System.currentTimeMillis());//获取当前系统时间
//                            String str = formatter.format(curDate);

                            Bitmap bitmap = ImageUtil.drawTextToRightBottom(TakefacePhotoScrollsActivity.this, bitmapByUrl, "", ChangeView.adjustFontSize(screenWidth, screenHeight), getResources().getColor(R.color.organger), 5, 5);
                            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
                            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
                            bos.flush();
                            bos.close();
                            returnResult(file, sn, snapTime, userId, personphotoUrl, faceRecgMark);
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                        } catch (IOException e) {

                        }


                    }
                });
    }

    @Override
    protected void onDestroy() {
        SharedPreferences sp = getSharedPreferences("CameraSwitchView",
                Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.clear();
        editor.commit();
        super.onDestroy();

        SandriosCamera.sandriosCameraClear();
    }

    private void returnResult(File file, Integer sn, String snapTime, String userId, String personphotoUrl, int faceRecgMark) {
        Uri uri = Uri.fromFile(file);
        String url = uri.toString().substring(uri.toString().indexOf("///") + 2);
        Intent intent = new Intent();
        // 设置要回传的数据
        intent.putExtra("url", url);

        // 设置回传码和Intent
        setResult(1, intent);
        finish();
        uploadImg(file, sn, snapTime, userId, personphotoUrl, faceRecgMark, url);
    }

    private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
    private final OkHttpClient client = new OkHttpClient();

    private void uploadImg(File mediaFile, Integer sn, String snapTime, String userId, String personphotoUrl, Integer faceRecgMark, String url) {
        // mImgUrls为存放图片的url集合
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        if (faceRecgMark == 1 || faceRecgMark == 2) {
            if (mediaFile != null) {
                builder.addFormDataPart("userPImg", mediaFile.getName(), RequestBody.create(MEDIA_TYPE_PNG, mediaFile));
                builder.addFormDataPart("sn", sn.toString());
                builder.addFormDataPart("userId", userId);
                builder.addFormDataPart("snapTime", snapTime);
                builder.addFormDataPart("photoUrl", personphotoUrl);
                builder.addFormDataPart("faceRecgMark", faceRecgMark.toString());
            }

            MultipartBody requestBody = builder.build();
            //构建请求
            Request request = new Request.Builder()
                    .url(AppInterfaceConfig.BASE_URL + "app/paper/uploadPaperImg")//地址
                    .post(requestBody)//添加请求体
                    .build();
            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    //       LogUtils.e("上传失败", e.getLocalizedMessage());

                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String str = response.body().string();
                    LogUtils.e("上传成功", str);
                    UpPhotoBean upPhotoBean = JSON.parseObject(str, UpPhotoBean.class);
                    String data = upPhotoBean.getData();
                    int code = upPhotoBean.getCode();
                    String msg = upPhotoBean.getMsg();
                    boolean result = upPhotoBean.isResult();
                    if (result) {

                        EventBus.getDefault().post(new MessageEventTest1(2, true, url, code, faceRecgMark, msg));

                    } else {
                        LogUtils.e("上传空值", data);
                        EventBus.getDefault().post(new MessageEventTest1(2, false, url, code, faceRecgMark, msg));
                    }


                }
            });
        } else if (faceRecgMark == 0) {
            if (mediaFile != null) {
                builder.addFormDataPart("userPImg", mediaFile.getName(), RequestBody.create(MEDIA_TYPE_PNG, mediaFile));
                builder.addFormDataPart("sn", sn.toString());
                builder.addFormDataPart("userId", userId);
                builder.addFormDataPart("snapTime", snapTime);
                builder.addFormDataPart("photoUrl", "");
                builder.addFormDataPart("faceRecgMark", faceRecgMark.toString());
            }

            MultipartBody requestBody = builder.build();
            //构建请求
            Request request = new Request.Builder()
                    .url(AppInterfaceConfig.BASE_URL + "app/paper/uploadPaperImg")//地址
                    .post(requestBody)//添加请求体
                    .build();
            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    //       LogUtils.e("上传失败", e.getLocalizedMessage());

                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String str = response.body().string();
                    LogUtils.e("上传成功", str);
                    UpPhotoBean upPhotoBean = JSON.parseObject(str, UpPhotoBean.class);
                    String data = upPhotoBean.getData();
                    int code = upPhotoBean.getCode();
                    String msg = upPhotoBean.getMsg();
                    boolean result = upPhotoBean.isResult();
                    if (result) {
                        EventBus.getDefault().post(new MessageEventTest1(2, true, url, code, faceRecgMark, msg));

                    } else {
                        LogUtils.e("上传空值", data);
                        EventBus.getDefault().post(new MessageEventTest1(2, false, url, code, faceRecgMark, msg));
                    }


                }
            });
        }

    }

    //图片旋转
    public static Bitmap rotaingImageView(int angle, Bitmap bitmap) {
        //旋转图片 动作
        Matrix matrix = new Matrix();
        ;
        matrix.postRotate(angle);
        System.out.println("angle2=" + angle);
        // 创建新的图片
        Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
                bitmap.getWidth(), bitmap.getHeight(), matrix, true);
        return resizedBitmap;
    }

    /**
     * 图片按比例大小压缩方法
     *
     * @param image （根据Bitmap图片压缩）
     * @return
     */
    public static Bitmap compressScale(Bitmap image) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        // 判断如果图片大于1M,进行压缩避免在生成图片（BitmapFactory.decodeStream）时溢出
        if (baos.toByteArray().length / 1024 > 1024) {
            baos.reset();// 重置baos即清空baos
            image.compress(Bitmap.CompressFormat.JPEG, 80, baos);// 这里压缩50%，把压缩后的数据存放到baos中
        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        // 开始读入图片，此时把options.inJustDecodeBounds 设回true了
        newOpts.inJustDecodeBounds = true;
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
        newOpts.inJustDecodeBounds = false;
        int w = newOpts.outWidth;
        int h = newOpts.outHeight;
        //Log.i(TAG, w + "---------------" + h);
        // 现在主流手机比较多是800*480分辨率，所以高和宽我们设置为
        // float hh = 800f;// 这里设置高度为800f
        // float ww = 480f;// 这里设置宽度为480f
        float hh = 600f;
        float ww = 450f;
        // 缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
        int be = 1;// be=1表示不缩放
        if (w > h && w > ww) {// 如果宽度大的话根据宽度固定大小缩放
            be = (int) (newOpts.outWidth / ww);
        } else if (w < h && h > hh) { // 如果高度高的话根据高度固定大小缩放
            be = (int) (newOpts.outHeight / hh);
        }
        if (be <= 0)
            be = 1;
        newOpts.inSampleSize = be; // 设置缩放比例
        // newOpts.inPreferredConfig = Config.RGB_565;//降低图片从ARGB888到RGB565
        // 重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
        isBm = new ByteArrayInputStream(baos.toByteArray());
        bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
        return bitmap;
        //return bitmap;
    }
}
